<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type == 'password'">
      <t-form-item name="account">
        <t-input v-model="formData.account" size="large" :placeholder="`${t('pages.login.input.account')}`">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          :placeholder="`${t('pages.login.input.password')}`"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>
      <t-form-item name="checked">
        <div class="check-container remember-pwd">
          <t-checkbox v-model="formData.checked">{{ t('pages.login.remember') }}</t-checkbox>
          <!-- <span class="tip">{{ t('pages.login.forget') }}</span> -->
        </div>
      </t-form-item>
    </template>

    <!-- 扫码登录 -->
    <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">{{ t('pages.login.wechatLogin') }}</span>
        <span class="refresh" @click="refreshQRCode">{{ t('pages.login.refresh') }} <t-icon name="refresh" /></span>
      </div>
      <img :src="qrCodeUrl" alt="QR Code" v-if="qrCodeUrl" />
    </template>

    <!-- 手机号登录 -->
    <template v-else>
      <t-form-item name="phone">
        <t-input v-model="formData.phone" size="large" :placeholder="t('pages.login.input.phone')">
          <template #prefix-icon>
            <t-icon name="mobile" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item class="verification-code" name="verifyCode">
        <t-input v-model="formData.verifyCode" size="large" :placeholder="t('pages.login.input.verification')" />
        <t-button size="large" variant="outline" :disabled="countDown > 0" @click="sendCode">
          {{ countDown == 0 ? t('pages.login.sendVerification') : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
    </template>

    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button block size="large" type="submit"> {{ t('pages.login.signIn') }} </t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">{{
        t('pages.login.accountLogin')
      }}</span>
      <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')">{{ t('pages.login.wechatLogin') }}</span>
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')">{{ t('pages.login.phoneLogin') }}</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import type { FormInstanceFunctions, FormRule, SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useCounter } from '@/hooks';
import { t } from '@/locales';
import { usePermissionStore, useUserStore } from '@/store';
import { checkQRCodeStatus, currentUser, generateQRCode} from '@/api/login';

const userStore = useUserStore();
const loginInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
const qrCodeUrl = ref('');
const uuid = ref(''); // 存储 uuid 的 ref
const INITIAL_DATA = {
  phone: loginInfo?.phone || '',
  username: loginInfo?.username || '',
  password: loginInfo?.password || '',
  email: loginInfo?.email || '',
  verifyCode: '',
  checked: loginInfo?.checked || false,
};

const FORM_RULES: Record<string, FormRule[]> = {
  phone: [{ required: true, message: t('pages.login.required.phone'), type: 'error' }],
  account: [{ required: true, message: t('pages.login.required.account'), type: 'error' }],
  password: [{ required: true, message: t('pages.login.required.password'), type: 'error' }],
  verifyCode: [{ required: true, message: t('pages.login.required.verification'), type: 'error' }],
};

const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);

const [countDown, handleCounter] = useCounter();

const switchType = (val: string) => {
  type.value = val;
  if (type.value === 'qrcode') {
    generateQRCodeImage();
  }
};

const router = useRouter();

const checkQRCodeStatusInterval = ref<NodeJS.Timeout | null>(null);
const startCheckingQRCodeStatus = () => {
  checkQRCodeStatusInterval.value = setInterval(async () => {
    try {
      console.log('Checking QR Code Status for UUID:', uuid.value);
      const response = await checkQRCodeStatus(uuid.value);
      console.log('检查二维码状态响应:', response);
      if (response) {
        if (response.token && response.tokenHead) {
          // 处理包含 token 和 tokenHead 的响应
          userStore.token = response.token;
          userStore.tokenHead = response.tokenHead;
          console.log('Token and Token Head set:', userStore.token, userStore.tokenHead); 
          userStore.userInfo = await currentUser();
          console.log('User Info:', userStore.userInfo);

          const permissionStore = usePermissionStore();
          permissionStore.getPerms();
          console.log('Permissions fetched');
          MessagePlugin.success('登录成功');
          router.push('/dashboard');
          clearInterval(checkQRCodeStatusInterval.value!);
        }
      }
    } catch (error) {
      console.error('检查二维码状态失败:', error);
      MessagePlugin.error('检查二维码状态失败');
      clearInterval(checkQRCodeStatusInterval.value!);
    }
  }, 5000); // 每5秒检查一次状态
};

const generateQRCodeImage = async () => {
  try {
    const response = await generateQRCode();
    if (response) {
      qrCodeUrl.value = response.imageUrl;
      uuid.value = response.uuid;
      startCheckingQRCodeStatus();
    } else {
      throw new Error('生成二维码失败: response 不存在');
    }
  } catch (error) {
    console.error('生成二维码失败:', error);
    MessagePlugin.error('生成二维码失败');
  }
};
const refreshQRCode = () => {
  if (checkQRCodeStatusInterval.value) {
    clearInterval(checkQRCodeStatusInterval.value);
  }
  generateQRCodeImage();
};
// 在组件挂载时生成二维码
onMounted(() => {
  if (type.value === 'qrcode') {
    generateQRCodeImage();
  }
});

// 在组件卸载时清理 URL
onUnmounted(() => {
  if (qrCodeUrl.value) {
    URL.revokeObjectURL(qrCodeUrl.value);
  }
  if (checkQRCodeStatusInterval.value) {
    clearInterval(checkQRCodeStatusInterval.value);
  }
});
/**
 * 发送验证码
 */
const sendCode = () => {
  form.value.validate({ fields: ['phone'] }).then((e) => {
    if (e === true) {
      handleCounter();
    }
  });
};

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      const { account, password } = formData.value;
      let userInfo: { username?: string; email?: string; phone?: string; password: string } = { password };

      if (/\d{11}/.test(account)) {
        userInfo.phone = account;
      } else if (/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(account)) {
        userInfo.email = account;
      } else {
        userInfo.username = account;
      }

      await userStore.login(userInfo);

      MessagePlugin.success('登录成功');
      if (formData.value.checked) {
        const { checked, account, password } = formData.value;
        localStorage.setItem('loginInfo', JSON.stringify({ checked, account, password }));
      }
      router.push('/dashboard');
    } catch (e) {
      console.log(e);
      MessagePlugin.error(e.message);
    }
  }
};
</script>

<style lang="less" scoped>
@import '../index.less';
</style>